//
//  WDGroMoreBmsReportManager.m
//  WDGroMore
//
//  Created by little People on 2023/8/1.
//

#import "WDGroMoreBmsReportManager.h"
#import <CommonCrypto/CommonDigest.h>
#import "WDGroMoreHeader.h"
@implementation WDGroMoreBmsReportManager
{
    NSString *loginUUID;
}
static WDGroMoreBmsReportManager *_manager = nil;

+ (instancetype)manager
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _manager = [[self alloc] init];
        
    });
    return _manager;
}

- (void)rewardVideoBmsEventWithEventName:(NSString *)eventName rewardVideoAd:(BUNativeExpressRewardedVideoAd *)rewardVideoAd
{
    
}

- (void)purchaseBmsEventWithProductId:(NSString *)productId andPamt:(NSString *)pamt andOrderNumber:(NSString *)orderNumber
{
    


    NSString *m_data = [self purchaseM_dataWithProductId:(NSString *)productId andPamt:(NSString *)pamt];
    NSDictionary *param = @{@"timestamp":[self timestamp],
                            @"nonce":[NSString stringWithFormat:@"%@%@",[self timestamp],[self getNonceString]],
                            @"app_name":[WDGroMoreJosnManager bmsAppNameForInfoPlistFile],
                            @"channel":[WDGroMoreJosnManager bmsChannelForSDKConfigFile],
                            @"version":[WDGroMoreJosnManager bmsAppVersionForInfoPlistFile],
                            @"uuid":[WDGroMorePublic manager].WDGetUUID,
                            @"podr":orderNumber,
                            @"m_data":[NSString stringWithFormat:@"[%@]",m_data],
                            @"use_service_time":@"1"
    };
    NSLog(@"bmsEvent para:%@",param);
    NSLog(@"md5的字符串:%@",[NSString stringWithFormat:@"%@%@",[self changeParamsToString:param],REQUEST_SECRET]);
    NSString *sign = [self wm_md5:[NSString stringWithFormat:@"%@%@",[self changeParamsToString:param],REQUEST_SECRET]];
    NSMutableDictionary *temp = [NSMutableDictionary dictionaryWithDictionary:param];
    [temp setValue:sign forKey:@"sign"];
    NSLog(@"result dict:%@",temp);
    [self postRequestWithParameter:[self changeParamsToString:temp] url:[NSString stringWithFormat:@"%@common/user-op/op-merge-report?trace_id=%@",REQUEST_URL,[self timestamp]] CompletionHandler:^(BOOL isSuccess, NSDictionary *dataDict) {
        if (isSuccess && dataDict)
        {
            NSString *code = [NSString stringWithFormat:@"%@",[dataDict objectForKey:@"code"]];
            NSString *msg = [NSString stringWithFormat:@"%@",[dataDict objectForKey:@"msg"]];
            NSLog(@"bmsEvent code:%@  msg:%@",code,msg);
        }
    }];
}

- (NSString *)purchaseM_dataWithProductId:(NSString *)productId andPamt:(NSString *)pamt
{
    
    NSDictionary *param = @{@"d_type":@"iap",
                            @"act":@"purchase_success",
                            @"t":[self timestamp],
                            @"pamt":pamt,
                            @"pdi":productId,
                            @"os":[NSString stringWithFormat:@"%@%@",[[UIDevice currentDevice] systemName],[[UIDevice currentDevice] systemVersion]],
                            @"idfa":[self getDeviceIDFA],
                            @"idfv":[self getDeviceIDFV],
                            @"platform":@"ios"
    };
    


    return [self convertToJSONData:param];
}

- (void)intersititialBmsEventWithEventName:(NSString *)eventName intersititialAd:(BUNativeExpressFullscreenVideoAd *)intersititialAd
{
    BUMRitInfo *info = [intersititialAd.mediation getShowEcpmInfo];
     NSLog(@"intersititialAd---ecpm:%@", info.ecpm);
     NSLog(@"platform:%@", info.adnName);
     NSLog(@"ritID:%@", info.slotID);
     NSLog(@"requestID:%@", info.requestID ?: @"None");
    
    if(info.slotID == nil){
        NSLog(@"info------:%@", info);
        return;
    }
    
    
    if (loginUUID.length <= 0)
    {
        [self getLoginUUIDCompletionHandler:^(BOOL isSuccess, NSString * _Nonnull uuid) {
            if (isSuccess && uuid.length > 0)
            {
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_global_queue(0, DISPATCH_QUEUE_PRIORITY_DEFAULT), ^{
                    [self bmsEventWithEventName:eventName adType:@"插屏全屏" networkName:[self adNetworkNameWithNetworkId:info.adnName] placementId:info.slotID];
                });
                
            }
        }];
    }
    else
    {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_global_queue(0, DISPATCH_QUEUE_PRIORITY_DEFAULT), ^{
            [self bmsEventWithEventName:eventName adType:@"插屏全屏" networkName:[self adNetworkNameWithNetworkId:info.adnName] placementId:info.slotID];
        });
      
    }
    
}

- (void)bannerBmsEventWithEventName:(NSString *)eventName bannerAd:(BUNativeExpressBannerView *)bannerAd
{
    BUMRitInfo *info = [bannerAd.mediation getShowEcpmInfo];
    NSLog(@"ecpm:%@", info.ecpm);
    NSLog(@"platform:%@", info.adnName);
    NSLog(@"ritID:%@", info.slotID);
    NSLog(@"requestID:%@", info.requestID ?: @"None");
    
    if(info.slotID == nil){
        NSLog(@"info------:%@", info);
        return;
    }
    
    if (loginUUID.length <= 0)
    {
        [self getLoginUUIDCompletionHandler:^(BOOL isSuccess, NSString * _Nonnull uuid) {
            if (isSuccess && uuid.length > 0)
            {
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_global_queue(0, DISPATCH_QUEUE_PRIORITY_DEFAULT), ^{
                    [self bmsEventWithEventName:eventName adType:@"bannerAd" networkName:[self adNetworkNameWithNetworkId:info.adnName] placementId:info.slotID];
                });
                
            }
        }];
    }
    else
    {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_global_queue(0, DISPATCH_QUEUE_PRIORITY_DEFAULT), ^{
            [self bmsEventWithEventName:eventName adType:@"bannerAd" networkName:[self adNetworkNameWithNetworkId:info.adnName] placementId:info.slotID];
        });
        
    }
}

/*
 WindMillAdnNoData   = -2,       // 暂时无真实数据，未获取到最佳广告，一般在未展示之前提前调用
 WindMillAdnCustom = -1,         // 自定义adn
 WindMillAdnNone = 0,            // 未知adn
 WindMillAdnMTG = 1,             // Mintegral
 WindMillAdnVungle = 4,          // Vungle
 WindMillAdnApplovin = 5,        // applovin
 WindMillAdnUnityAds = 6,        // unityads
 WindMillAdnIronsource = 7,      // ironsource
 WindMillAdnGroMore = 9,          // GroMore
 WindMillAdnAdmob = 11,          // 谷歌Admob
 WindMillAdnPangle = 13,         // 穿山甲
 WindMillAdnGDT = 16,            // 腾讯广点通
 WindMillAdnKs = 19,             // 快手
 WindMillAdnKlevin = 20,         // 游可赢
 WindMillAdnBaidu = 21,          // 百度联盟
 WindMillAdnGroMore = 22,        // GroMore
 WindMillAdnBeiZi = 27,          // AdScope
 */
- (NSString *)adNetworkNameWithNetworkId:(NSString*)networkAdTpye
{
    
    if([networkAdTpye isEqualToString:@"pangle"]){
        return @"穿山甲";
    }
    if([networkAdTpye isEqualToString:@"mintegral"]){
        return @"腾讯广点通";
    }
    if([networkAdTpye isEqualToString:@"ks"]){
        return @"快手";
    }
    return networkAdTpye;
    
//    switch (networkId) {
//        case WindMillAdnCustom:
//            return @"自定义adn";
//            break;
//        case WindMillAdnNone:
//            return @"未知adn";
//            break;
//        case WindMillAdnMTG:
//            return @"Mintegral";
//            break;
//        case WindMillAdnVungle:
//            return @"Vungle";
//            break;
//        case WindMillAdnApplovin:
//            return @"applovin";
//            break;
//        case WindMillAdnUnityAds:
//            return @"unityads";
//            break;
//        case WindMillAdnIronsource:
//            return @"ironsource";
//            break;
//        case WindMillAdnGroMore:
//            return @"GroMore";
//            break;
//        case WindMillAdnAdmob:
//            return @"谷歌Admob";
//            break;
//        case WindMillAdnPangle:
//            return @"穿山甲";
//            break;
//        case WindMillAdnGDT:
//            return @"腾讯广点通";
//            break;
//        case WindMillAdnKs:
//            return @"快手";
//            break;
//        case WindMillAdnKlevin:
//            return @"游可赢";
//            break;
//        case WindMillAdnBaidu:
//            return @"百度联盟";
//            break;
//        case WindMillAdnGroMore:
//            return @"GroMore";
//            break;
//        case WindMillAdnBeiZi:
//            return @"AdScope";
//            break;
//        default:
//            break;
//    }
    return @"未知adn";
}

- (NSString *)eventDescriptionWithEventName:(NSString *)eventName
{
    if ([eventName isEqualToString:BMS_EVENT_ad_button_click])
    {
        return @"广告按钮点击(广告点击)";
    }
    else if ([eventName isEqualToString:BMS_EVENT_ad_load_start])
    {
        return @"广告开始加载(广告请求)";
    }
    else if ([eventName isEqualToString:BMS_EVENT_ad_load_sucess])
    {
        return @"广告加载结果";
    }
    else if ([eventName isEqualToString:BMS_EVENT_ad_show_start])
    {
        return @"广告开始展示";
    }
    else if ([eventName isEqualToString:BMS_EVENT_ad_show_end])
    {
        return @"广告结束展示";
    }
    else if ([eventName isEqualToString:BMS_EVENT_ad_show_skip])
    {
        return @"广告跳过";
    }
    else if ([eventName isEqualToString:BMS_EVENT_ad_show_fail])
    {
        return @"广告失败";
    }
    return @"";
}

- (void)bmsEventWithEventName:(NSString *)eventName adType:(NSString *)adType networkName:(NSString *)networkName placementId:(NSString *)placementId
{
    NSString *m_data = [self m_dataWithEventName:eventName adType:adType networkName:networkName placementId:placementId];
    NSDictionary *param = @{@"timestamp":[self timestamp],
                            @"nonce":[NSString stringWithFormat:@"%@%@",[self timestamp],[self getNonceString]],
                            @"app_name":[WDGroMoreJosnManager bmsAppNameForInfoPlistFile],
                            @"channel":[WDGroMoreJosnManager bmsChannelForSDKConfigFile],
                            @"version":[WDGroMoreJosnManager bmsAppVersionForInfoPlistFile],
                            @"uuid":[WDGroMorePublic manager].WDGetUUID,
                            @"m_data":[NSString stringWithFormat:@"[%@]",m_data],
                            @"use_service_time":@"1"
    };
    NSLog(@"bmsEvent para:%@",param);
    NSLog(@"md5的字符串:%@",[NSString stringWithFormat:@"%@%@",[self changeParamsToString:param],REQUEST_SECRET]);
    NSString *sign = [self wm_md5:[NSString stringWithFormat:@"%@%@",[self changeParamsToString:param],REQUEST_SECRET]];
    NSMutableDictionary *temp = [NSMutableDictionary dictionaryWithDictionary:param];
    [temp setValue:sign forKey:@"sign"];
    NSLog(@"result dict:%@",temp);
    [self postRequestWithParameter:[self changeParamsToString:temp] url:[NSString stringWithFormat:@"%@common/user-op/op-merge-report?trace_id=%@",REQUEST_URL,[self timestamp]] CompletionHandler:^(BOOL isSuccess, NSDictionary *dataDict) {
        if (isSuccess && dataDict)
        {
            NSString *code = [NSString stringWithFormat:@"%@",[dataDict objectForKey:@"code"]];
            NSString *msg = [NSString stringWithFormat:@"%@",[dataDict objectForKey:@"msg"]];
            NSLog(@"bmsEvent code:%@  msg:%@",code,msg);
        }
    }];
}

- (NSString *)m_dataWithEventName:(NSString *)eventName adType:(NSString *)adType networkName:(NSString *)networkName placementId:(NSString *)placementId
{
    NSLog(@"m_dataWithEventName-----%@-----%@-----%@------%@",eventName,adType,networkName,placementId);
    
    NSDictionary *param = @{@"d_type":@"ad_ac",
                            @"t":[self timestamp],
                            @"tab1":networkName,
                            @"tab2":placementId,
                            @"act":eventName,
                            @"ad_t":adType,
                            @"wds":[self eventDescriptionWithEventName:eventName],
                            @"os":[NSString stringWithFormat:@"%@%@",[[UIDevice currentDevice] systemName],[[UIDevice currentDevice] systemVersion]],
                            @"idfa":[self getDeviceIDFA],
                            @"idfv":[self getDeviceIDFV],
                            @"platform":@"ios"
    };
    


    return [self convertToJSONData:param];
}

- (void)getLoginUUIDCompletionHandler:(void (^)(BOOL isSuccess, NSString* uuid))completionHandler
{
    NSDictionary *param = @{@"app_name":[WDGroMoreJosnManager bmsAppNameForInfoPlistFile],
                            @"openid":[self getOpenId],
                            @"idfa":[self getDeviceIDFA],
                            @"idfv":[self getDeviceIDFV],
                            @"timestamp":[self timestamp],
                            @"nonce":[NSString stringWithFormat:@"%@%@",[self timestamp],[self getNonceString]],
                            @"platform":@"ios"
    };
    NSLog(@"md5的字符串:%@",[NSString stringWithFormat:@"%@%@",[self changeParamsToString:param],REQUEST_SECRET]);
    NSString *sign = [self wm_md5:[NSString stringWithFormat:@"%@%@",[self changeParamsToString:param],REQUEST_SECRET]];
    NSMutableDictionary *temp = [NSMutableDictionary dictionaryWithDictionary:param];
    [temp setValue:sign forKey:@"sign"];
    [self postRequestWithParameter:[self changeParamsToString:temp] url:[NSString stringWithFormat:@"%@common/w-sdk/login",REQUEST_URL] CompletionHandler:^(BOOL isSuccess, NSDictionary *dataDict) {
        if (isSuccess && dataDict)
        {
            NSString *code = [NSString stringWithFormat:@"%@",[dataDict objectForKey:@"code"]];
            if ([code isEqualToString:@"0"])
            {
                NSDictionary *data = dataDict[@"data"];
                NSString *uuid = [NSString stringWithFormat:@"%@",data[@"uuid"]];
                self->loginUUID = uuid;
                NSLog(@"uuid:%@",uuid);
                completionHandler(YES,uuid);
            }
            else
            {
                NSLog(@"message:%@",[NSString stringWithFormat:@"%@",dataDict[@"msg"]]);
                completionHandler(NO,@"");
            }
        }
    }];
}

- (void)postRequestWithParameter:(NSString *)para url:(NSString *)url CompletionHandler:(void (^)(BOOL isSuccess, NSDictionary* dataDict))completionHandler
{
    //1.创建URL对象
//    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@common/w-sdk/login",REQUEST_URL]];
    NSLog(@"url:%@",url);
    //2.创建请求对象
    //第一个参数是你的URL
    //第二个参数是请求的缓存策略
    //第三个参数是设置请求超时时间
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
    //3.设置请求方法为post
    [request setHTTPMethod:@"POST"];
    NSLog(@"post para:%@",para);
    request.HTTPBody = [para dataUsingEncoding:NSUTF8StringEncoding];
    //6.建立会话 session支持三种类型的任务
    //    NSURLSessionDataTask  //加载数据
    //    NSURLSessionDownloadTask  //下载
    //    NSURLSessionUploadTask   //上传
    NSURLSession *session = [NSURLSession sharedSession];
    //7.创建请求任务
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        //data就是你获取到的数据，你可以自行对其进行解析
        //error就是获取失败时出现的问题
        if (!error)
        {
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
            completionHandler(YES,dict);
//            NSLog(@"post dict:%@",dict);
//            NSString *code = [NSString stringWithFormat:@"%@",[dict objectForKey:@"code"]];
//            if ([code isEqualToString:@"0"])
//            {
//                NSDictionary *dataDict = dict[@"data"];
//                NSString *uuid = [NSString stringWithFormat:@"%@",dataDict[@"uuid"]];
//                NSLog(@"uuid:%@",uuid);
//                completionHandler(YES,uuid);
//            }
//            else
//            {
//                NSLog(@"message:%@",[NSString stringWithFormat:@"%@",dict[@"msg"]]);
//                completionHandler(NO,@"");
//            }
        }
        else
        {
            NSLog(@"error:%@",error);
            completionHandler(NO,nil);
        }
        
    }];
    //8.启动任务
    [dataTask resume];
}

#pragma mark parameter
/// OpenId
- (NSString *)getOpenId {
    // 设置openID
    NSString *openId = [[WDGroMoreDataPersistenceManager manager] getDataWithKey:DataPersistence_UUID_key];
    if (openId.length <= 0) {
        NSString *deviceUUID = [self getDeviceUUID];
        deviceUUID = [deviceUUID stringByReplacingOccurrencesOfString:@"-" withString:@""];
        openId = [NSString stringWithFormat:@"iOS_%@",deviceUUID];
        [[WDGroMoreDataPersistenceManager manager] saveData:openId AndKey:DataPersistence_UUID_key];
    }
    return openId;
}

- (NSString *)timestamp {
    NSUInteger time = [[NSDate dateWithTimeIntervalSinceNow:0] timeIntervalSince1970];
    return [NSString stringWithFormat:@"%lu", (unsigned long)time];
}

/// 生成 30分钟内唯一 的长度在 大于等于16小于等于64 之间的字符串
- (NSString *)getNonceString {
    
    /*
     必须保证30分钟内唯一， 长度须大于等于16小于等于64 , 只能包含大小写字母、下划线、0到9这些，正则表示：^[_a-zA-Z0-9]{32}$
     */
    
    NSString *randomString = [self getDeviceUUID];
    randomString = [randomString stringByReplacingOccurrencesOfString:@"-" withString:@""];
    return randomString;
}

- (NSString *)getDeviceIDFA
{
    NSString *idfaString = [[ASIdentifierManager sharedManager] advertisingIdentifier].UUIDString;
    return idfaString;
}

- (NSString *)getDeviceUUID {
    return [[NSUUID UUID] UUIDString];
}

- (NSString *)getDeviceIDFV {
    return [[UIDevice currentDevice].identifierForVendor UUIDString];
}

- (NSString*)convertToJSONData:(id)infoDict
{

    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:infoDict
                                                       options:0 // Pass 0 if you don't care about the readability of the generated string
                                                         error:&error];

    NSString *jsonString = @"";
    
    if (! jsonData)
    {
        NSLog(@"Got an error: %@", error);
    }else
    {
        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }

    jsonString = [jsonString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];  //去除掉首尾的空白字符和换行字符

    [jsonString stringByReplacingOccurrencesOfString:@"\n" withString:@""];

    return jsonString;
}

- (NSString *)changeParamsToString:(NSDictionary *)params {
    // 参数拼接
    NSMutableString *paramsString = [[NSMutableString alloc] init];
    // 取出参数中所有的key值
    NSArray *allKeysFromDic = params.allKeys;
    NSArray*sortedArray = [allKeysFromDic sortedArrayUsingComparator:^NSComparisonResult(id obj1,id obj2) {
        return [obj1 compare:obj2 options:NSNumericSearch];//正序
    }];
    
    for (int i =0 ; i < sortedArray.count; i++)  {
        NSString *key = sortedArray[i];
        NSString *value = params[key];
        
        [paramsString appendFormat:@"%@=%@", key, value];
        if (i < params.count - 1) {
            [paramsString appendString:@"&"];
        }
    }
    return paramsString;
}

- (NSString *)wm_md5:(NSString *)string {
    const char *cStr = [string UTF8String];
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    CC_MD5(cStr, (CC_LONG)strlen(cStr), digest);
    NSMutableString *result = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
        [result appendFormat:@"%02x", digest[i]];
    }
    return result;
}

@end
